package com.dd.cloud.common.config.common;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Get请求 时间类型转换
 *
 * @author zk
 */
@Configuration
public class DateConverterConfig {
    public static final String DEFAULT_DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";

    interface LocalDateConverter extends Converter<String, LocalDate> {

    }

    @Bean
    public LocalDateConverter localDateConverter() {
        return s -> LocalDate.parse(s, DateTimeFormatter.ofPattern(DEFAULT_DATE_PATTERN));
    }

    interface LocalDateTimeConverter extends Converter<String, LocalDateTime> {

    }

    @Bean
    public LocalDateTimeConverter localDateTimeConverter() {
        return s -> {
            if (s.length() == DEFAULT_DATE_PATTERN.length()) {
                s += " 00:00:00";
            }
            return LocalDateTime.parse(s, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_PATTERN));
        };
    }
}
